package com.nervenets.template.event;

import com.nervenets.general.utils.JodaUtils;
import com.nervenets.general.web.params.QueryParams;
import com.nervenets.template.hibernate.domain.order.RechargeOrder;
import com.nervenets.template.hibernate.domain.user.User;
import com.nervenets.template.service.DataOfUserService;
import com.nervenets.template.service.RechargeOrderService;
import com.nervenets.template.service.UserService;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.Async;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.List;

@Slf4j
@AllArgsConstructor
public class DataOfUserEventListener {
    private final DataOfUserService dataOfUserService;
    private final UserService userService;
    private final RechargeOrderService rechargeOrderService;

    @SneakyThrows
    @Async
    @Order(0)
    @EventListener(DataOfUserEvent.class)
    public void handle(DataOfUserEvent event) {
        Thread.sleep(1000);

        DataOfUserEvent.Type type = (DataOfUserEvent.Type) event.getSource();
        long newer = 0, pay = 0, classesPay = 0, teacherPay = 0, coursePay = 0, transferPay = 0, refund = 0;
        switch (type) {
            case newer:
                newer = userService.count(new QueryParams<User>() {
                    @Override
                    public void generateSpecification(List<Predicate> predicates, Root<User> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
                        predicates.add(builder.between(root.get("createTime"), JodaUtils.getStartOfToday(), JodaUtils.getEndOfToday()));
                    }
                });
                break;
            case pay:
                pay = rechargeOrderService.count(new QueryParams<RechargeOrder>() {
                    @Override
                    public void generateSpecification(List<Predicate> predicates, Root<RechargeOrder> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
                        predicates.add(builder.between(root.get("createTime"), JodaUtils.getStartOfToday(), JodaUtils.getEndOfToday()));
                    }
                });
                break;
            case refund:
                break;
        }
        dataOfUserService.updateData(newer, pay, classesPay, teacherPay, coursePay, transferPay, refund);
    }
}
